﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Configuration;
using System.IO;

using LibSnesDotNet.UI;
using LibSnesDotNet.Input;

namespace LibSnesDotNet
{
	public class Configuration : INotifyPropertyChanged
	{
		ExeConfigurationFileMap _map;
		System.Configuration.Configuration _config;
		ConfigurationSectionGroup _group;

		public Configuration(ExeConfigurationFileMap map)
		{
			_map = map;

			Load();
		}

		public event PropertyChangedEventHandler PropertyChanged;

		public UISection UI
		{
			get { return (UISection)_group.Sections["ui"]; }
			set
			{
				_group.Sections.Remove("ui");
				_group.Sections.Add("ui", value);

				if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("UI")); }
			}
		}

		public InputSection Input
		{
			get { return (InputSection)_group.Sections["input"]; }
			set
			{
				_group.Sections.Remove("input");
				_group.Sections.Add("input", value);

				if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("input")); }
			}
		}

		public void Save()
		{
			_config.Save();
		}

		public void Load()
		{
			do
			{
				try
				{
					_config = ConfigurationManager.OpenMappedExeConfiguration(_map, ConfigurationUserLevel.PerUserRoaming);
					_group = _config.SectionGroups["libSnesDotNet"];

					if (_group != null)
					{
						_group.Validate();
					}
					else
					{
						_group = new ConfigurationSectionGroup();
						_config.SectionGroups.Add("libSnesDotNet", _group);
					}
				}
				catch
				{
					var result = System.Windows.MessageBox.Show("Configuration is invalid. Restore defaults instead?", "Error",
					                                            System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Error);
					if (result == System.Windows.MessageBoxResult.Yes)
					{
						_group = null;
						File.Delete(_map.RoamingUserConfigFilename);
					}
					else
					{
						return;
					}
				}
			} while (_group == null);

			if (UI == null) { UI = new UISection(); }
			if (Input == null) { Input = new InputSection(); }
		}
	}
}
